package com.kunge2013.service.registry.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author kunge2013
 * @Description zk客户端初始化
 * @Date 2024/10/28 12:54
 * @Version 1.0
 */
@Configuration
@Slf4j
public class ZkConfig {
    @Bean
    public CuratorFramework zkClient(ZookeeperConfig zookeeperConfig) {
        //重试策略，初试时间1秒，重试10次
        RetryPolicy policy = new ExponentialBackoffRetry(
                zookeeperConfig.getBaseSleepTimeMs(),
                zookeeperConfig.getMaxRetries());
        //通过工厂创建Curator
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zookeeperConfig.getServer())
                .authorization("digest",zookeeperConfig.getDigest().getBytes())
                .connectionTimeoutMs(zookeeperConfig.getConnectionTimeoutMs())
                .sessionTimeoutMs(zookeeperConfig.getSessionTimeoutMs())
                .retryPolicy(policy).build();
        //开启连接
        client.start();
        log.info("zookeeper 初始化完成...");
        return client;
    }
}
